import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/dio/community.dart';
import 'package:hkzf_flutter/dio/general_type.dart';
import 'package:hkzf_flutter/scoped_model/auth_model.dart';
import 'package:hkzf_flutter/utils/common_toast.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/public.dart';
import 'package:hkzf_flutter/utils/scoped_model_helper.dart';
import 'package:hkzf_flutter/utils/upload_image.dart';
import 'package:hkzf_flutter/widgets/common_form_item.dart';
import 'package:hkzf_flutter/widgets/common_image_picker.dart';
import 'package:hkzf_flutter/widgets/common_radio_form_item.dart';
import 'package:hkzf_flutter/widgets/common_select_form_item.dart';
import 'package:hkzf_flutter/widgets/common_title.dart';
import 'package:hkzf_flutter/widgets/common_floating_button.dart';
import 'package:hkzf_flutter/widgets/room_appliance_item.dart';

// 房源发布页

class RoomAddPage extends StatefulWidget {
  const RoomAddPage({super.key});

  @override
  State<RoomAddPage> createState() => _RoomAddPageState();
}

class _RoomAddPageState extends State<RoomAddPage> {

  int rentType = 0;// 租赁方式
  int decorationType = 0;// 装修方式

  int roomTyep = 0;//  房屋类型
  int floor = 0;//  楼层
  int oriented = 0;//  朝向
  
  // 房屋标题文字输入控制器
  TextEditingController titleController = TextEditingController();
  // 房屋描述文字输入控制器
  TextEditingController descController = TextEditingController();

  // 户型数据集
  List<GeneralType> roomTypeList = [];
  // 朝向数据集
  List<GeneralType> orientedList = [];
  // 楼层数据集
  List<GeneralType> floorList = [];
  // 选择的小区
  Community? community;

  // 选择的图片列表
  List<File> images = [];

  // 房屋配置列表
  List<RoomApplianceItem> roomApplianceList = [];

  // 初始化设置数据
  _getData() async{
    // 发送请求
    var path = '/houses/params';
    var res =await DioHttp.of(context).get(path);
    var data = json.decode(res.toString())['body'];
    List<GeneralType> roomTypeList = (data['roomType'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> orientedList = (data['oriented'] as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    List<GeneralType> floorList =(data['floor']  as List)
    .map((item)=>GeneralType.fromJson(item as Map<String, dynamic>)).toList();
    setState(() {
      this.roomTypeList = roomTypeList;
      this.orientedList = orientedList;
      this.floorList = floorList;
    });
  }

  @override
  void initState() {
    // 确保在 UI 完成构建后再进行某些操作（如数据加载）
    WidgetsBinding.instance.addPostFrameCallback((_) {
       _getData();
    });
    super.initState();
  }
  var sizeController = TextEditingController();
  var priceController = TextEditingController();
  // 提交表单
  _submit() async{
    var imageString = await uploadImages(images,context);
    var price = priceController.text.trim();
    var size = sizeController.text.trim();
    if(isNullOrEmpty(price)){
      return CommonToast.showToast('租金价格不能为空');
    }
    if(isNullOrEmpty(size)){
      return CommonToast.showToast('房屋大小不能为空');
    }
    // 提交参数
    Map<String,dynamic> params = {
      "title": titleController.text,
      "description": descController.text,
      "price": price,
      "size": size,
      "oriented": orientedList[oriented].id,
      "roomType": roomTypeList[roomTyep].id,
      "floor": floorList[floor].id,
      "community": community?.id,
      "houseImg": imageString,// 多条以 | 分割
      "supporting": roomApplianceList.map((item)=>item.title).join('|'),
    };
    print('房源发布配置参数：$params');
    // 获取状态存储中的token信息
    var token = ScopedModelHelper.getModel<AuthModel>(context).token;
    
    var path = '/user/houses';
    var res = await DioHttp.of(context).post(path,params,token);
    var status = json.decode(res.toString())['status'];
    if(status.toString().startsWith('2')){
      CommonToast.showToast('房源发布成功');
      Navigator.of(context).pop(true);
    }else{
      var desc = json.decode(res.toString())['description'];
      CommonToast.showToast(desc);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("房源发布"),
        backgroundColor: Colors.green,
      ),
      floatingActionButton: CommonFloatingButton(
        title: '提交', 
        onTap: ()=>_submit(),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      body: ListView(
        children: [
          const CommonTitle(title: '房源信息',),
          CommonFormItem(
            label: '小区',
            contentBuilder: (context){
              return GestureDetector(
                  // HitTestBehavior.opaque	拦截所有点击事件，阻止事件传递给下层 widget
                  // HitTestBehavior.translucent	接收点击事件，但允许事件继续传递给下层 widget
                  // HitTestBehavior.deferToChild	不处理事件，将点击事件交给子 widget 处理
                  behavior: HitTestBehavior.translucent,//控制手势事件穿透行为
                  onTap: (){
                    var result= Navigator.pushNamed(context, '/communityPicker');
                    result.then((value) { 
                      if(value!=null){ 
                        setState(() {
                          community = value as Community;
                        });
                      }
                    });
                  },
                  child: SizedBox(
                    height: 40.0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          community?.name ??'请选择小区',
                          style: const TextStyle(fontSize: 16.0),
                        ),
                        const Icon(Icons.keyboard_arrow_right,size: 30.0,),
                      ],
                    ),
                  ),
                );
            },
          ),
          CommonFormItem(
            label: '租金',
            hintText: '请输入租金',
            suffixText: '元/月',
            controller: priceController,
          ),
          CommonFormItem(
            label: '大小',
            hintText: '请输入房屋大小',
            suffixText: '平方米',
            controller: sizeController,
          ),
          CommonRadioFormItem(
            label: '租赁方式',
            options: const ['合租','整租'],
            value: rentType,
            onChanged: (index){
              setState(() {
                rentType = index;
              });
            },
          ),
          CommonRadioFormItem(
            label: '装修',
            options: const ['精装','简装'],
            value: decorationType,
            onChanged: (index){
              setState(() {
                decorationType = index;
              });
            },
          ),
          CommonSelectFormItem(
            label: '户型',
            value: roomTyep,
            options: roomTypeList.isNotEmpty? roomTypeList.map((item)=>item.name as String).toList():[''],
            onChanged: (index){
              setState(() {
                roomTyep = index;
              });
            },
          ),
          CommonSelectFormItem(
            label: '楼层',
            value: floor,
            options: floorList.isNotEmpty? floorList.map((item)=>item.name as String).toList():[''],
            onChanged: (index){
              setState(() {
                floor = index;
              });
            },
          ),
          CommonSelectFormItem(
            label: '朝向',
            value: oriented,
            options: orientedList.isNotEmpty? orientedList.map((item)=>item.name as String).toList():[''],
            onChanged: (index){
              setState(() {
                oriented = index;
              });
            },
          ),
          const CommonTitle(title: '房屋图像',),
          CommonImagePicker(
            onChanged: (list) {
              print('触发回调$list');
              // 图表改变回调事件
              setState(() {
                images = list;
              });
            },
          ),
          const CommonTitle(title: '房屋标题',),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: TextField(
              controller: titleController,
              decoration: const InputDecoration(
                hintText: '请输入标题 (例如：整租, 小区2室2000元)',
                border: InputBorder.none,
              ),
            ),
          ),
          const CommonTitle(title: '房屋配置',),
          RoomApplianceItemWidget(onChange:(data){
            print('房屋配置数据: $data');
            setState(() {
              roomApplianceList = data;
            });
          }),
          const CommonTitle(title: '房屋描述',),
           Container(
            margin: const EdgeInsets.only(bottom: 90.0),
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: TextField(
              controller: descController,
              decoration: const InputDecoration(
                hintText: '请输入房屋描述信息',
                border: InputBorder.none,
              ),
            ),
          ),

        ],
      ),
    );
  }
}